<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请用户ID" prop="userId" label-width="100px">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入申请用户ID"
          clearable
          type="number"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目标用户ID" prop="targetUserId" label-width="100px">
        <el-input
          v-model="queryParams.targetUserId"
          placeholder="请输入目标用户ID"
          clearable
          type="number"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="红娘ID" prop="matchmakerId">
        <el-input
          v-model="queryParams.matchmakerId"
          placeholder="请输入红娘ID"
          clearable
          type="number"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['request:request:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestList">
      <el-table-column label="申请ID" align="center" prop="requestId" width="80" />
      <el-table-column label="申请用户ID" align="center" prop="userId" width="100" />
      <el-table-column label="目标用户ID" align="center" prop="targetUserId" width="100" />
      <el-table-column label="红娘ID" align="center" prop="matchmakerId" width="80">
        <template #default="scope">
          <span v-if="scope.row.matchmakerId">{{ scope.row.matchmakerId }}</span>
          <span v-else style="color: #909399;">系统分配</span>
        </template>
      </el-table-column>
      <el-table-column label="申请留言" align="center" prop="requestMessage" width="200" show-overflow-tooltip />
      <el-table-column label="申请状态" align="center" prop="requestStatus" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.requestStatus === 0" type="warning">待处理</el-tag>
          <el-tag v-else-if="scope.row.requestStatus === 1" type="success">已接受</el-tag>
          <el-tag v-else-if="scope.row.requestStatus === 2" type="danger">已拒绝</el-tag>
          <el-tag v-else-if="scope.row.requestStatus === 3" type="info">已完成</el-tag>
          <el-tag v-else-if="scope.row.requestStatus === 4" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒绝原因" align="center" prop="rejectReason" width="150" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="User"
            @click="handleViewUser(scope.row.userId)"
            v-hasPermi="['request:request:query']">
            申请用户详情
          </el-button>
          <el-button
            link
            type="success"
            icon="User"
            @click="handleViewUser(scope.row.targetUserId)"
            v-hasPermi="['request:request:query']">
            目标用户详情
          </el-button>
          <el-button
            v-if="scope.row.matchmakerId"
            link
            type="warning"
            icon="Star"
            @click="handleViewMatchmaker(scope.row.matchmakerId)"
            v-hasPermi="['request:request:query']">
            红娘详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" v-model="userDetailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border v-if="userDetail">
        <el-descriptions-item label="用户ID">{{ userDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ userDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ userDetail.nickname }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag v-if="userDetail.gender === 1" type="primary">男</el-tag>
          <el-tag v-else-if="userDetail.gender === 2" type="danger">女</el-tag>
          <span v-else>未知</span>
        </el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ parseTime(userDetail.birthDate, '{y}-{m}-{d}') || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="头像" :span="2">
          <el-image
            v-if="userDetail.avatarUrl"
            :src="userDetail.avatarUrl"
            style="width: 100px; height: 100px; border-radius: 50%;"
            fit="cover"
            :preview-src-list="[userDetail.avatarUrl]"
          />
          <span v-else>暂无头像</span>
        </el-descriptions-item>
        <el-descriptions-item label="用户角色">
          <el-tag v-if="userDetail.userRole === 1" type="info">普通用户</el-tag>
          <el-tag v-else-if="userDetail.userRole === 2" type="success">红娘</el-tag>
          <span v-else>未知</span>
        </el-descriptions-item>
        <el-descriptions-item label="粉丝数">{{ userDetail.fan || 0 }}</el-descriptions-item>
        <el-descriptions-item label="关注数">{{ userDetail.countFollow || 0 }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ userDetail.countLike || 0 }}</el-descriptions-item>
        <el-descriptions-item label="账号状态">
          <el-tag v-if="userDetail.accountStatus === 1" type="success">正常</el-tag>
          <el-tag v-else-if="userDetail.accountStatus === 0" type="danger">冻结</el-tag>
          <el-tag v-else-if="userDetail.accountStatus === 2" type="info">注销</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="实名认证">
          <el-tag v-if="userDetail.isVerified === 1" type="success">已认证</el-tag>
          <el-tag v-else type="warning">未认证</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="VIP状态">
          <el-tag v-if="userDetail.isVip === 1" type="warning">VIP用户</el-tag>
          <span v-else>普通用户</span>
        </el-descriptions-item>
        <el-descriptions-item label="VIP过期时间" v-if="userDetail.isVip === 1">
          {{ parseTime(userDetail.vipExpireTime, '{y}-{m}-{d}') || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ parseTime(userDetail.registerTime, '{y}-{m}-{d} {h}:{i}:{s}') || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="最后登录时间">{{ parseTime(userDetail.lastLoginTime, '{y}-{m}-{d} {h}:{i}:{s}') || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="最后登录IP">{{ userDetail.lastLoginIp || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(userDetail.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(userDetail.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') || '暂无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userDetailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 红娘详情对话框 -->
    <el-dialog title="红娘详情" v-model="matchmakerDetailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border v-if="matchmakerDetail">
        <el-descriptions-item label="红娘ID">{{ matchmakerDetail.matchmakerId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ matchmakerDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ matchmakerDetail.realName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ matchmakerDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ matchmakerDetail.idCardNo }}</el-descriptions-item>
        <el-descriptions-item label="红娘等级">
          <el-tag v-if="matchmakerDetail.matchmakerLevel === 1" type="info">预备红娘</el-tag>
          <el-tag v-else-if="matchmakerDetail.matchmakerLevel === 2" type="success">正式红娘</el-tag>
          <el-tag v-else-if="matchmakerDetail.matchmakerLevel === 3" type="warning">金牌红娘</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="服务区域">{{ matchmakerDetail.serviceArea }}</el-descriptions-item>
        <el-descriptions-item label="从业年限">{{ matchmakerDetail.serviceYears }}年</el-descriptions-item>
        <el-descriptions-item label="成功牵线次数">{{ matchmakerDetail.successCount }}次</el-descriptions-item>
        <el-descriptions-item label="红娘状态">
          <el-tag v-if="matchmakerDetail.matchmakerStatus === 1" type="success">正常</el-tag>
          <el-tag v-else type="danger">冻结</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="个人介绍" :span="2">{{ matchmakerDetail.introduction }}</el-descriptions-item>
        <el-descriptions-item label="资质证书" :span="2">
          <div v-if="getCertificationImages(matchmakerDetail.certification).length > 0" class="certification-images">
            <el-image
              v-for="(img, index) in getCertificationImages(matchmakerDetail.certification)"
              :key="index"
              :src="img"
              style="width: 200px; height: 150px; margin-right: 10px; margin-bottom: 10px;"
              :preview-src-list="getCertificationImages(matchmakerDetail.certification)"
              fit="cover"
            />
            <div class="certification-labels">
              <span v-for="(img, index) in getCertificationImages(matchmakerDetail.certification)" :key="'label-' + index"
                    style="display: inline-block; width: 200px; margin-right: 10px; text-align: center; color: #666; font-size: 12px;">
                {{ index === 0 ? '资质证书正面' : index === 1 ? '资质证书反面' : `证件${index + 1}` }}
              </span>
            </div>
          </div>
          <span v-else>暂无资质证书</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(matchmakerDetail.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(matchmakerDetail.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="matchmakerDetailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Request">
import { listRequest, getUserInfo, getMatchmakerInfo } from "@/api/request/request"

const { proxy } = getCurrentInstance()

// 牵线申请表格数据
const requestList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)

// 用户详情对话框
const userDetailOpen = ref(false)
const userDetail = ref(null)

// 红娘详情对话框
const matchmakerDetailOpen = ref(false)
const matchmakerDetail = ref(null)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    targetUserId: null,
    matchmakerId: null
  }
})

const { queryParams } = toRefs(data)

/** 查询牵线申请列表 */
function getList() {
  loading.value = true
  listRequest(queryParams.value).then(response => {
    requestList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 查看用户详情 */
function handleViewUser(userId) {
  getUserInfo(userId).then(response => {
    userDetail.value = response.data
    userDetailOpen.value = true
  }).catch(() => {
    proxy.$modal.msgError("获取用户详情失败")
  })
}

/** 查看红娘详情 */
function handleViewMatchmaker(matchmakerId) {
  getMatchmakerInfo(matchmakerId).then(response => {
    matchmakerDetail.value = response.data
    matchmakerDetailOpen.value = true
  }).catch(() => {
    proxy.$modal.msgError("获取红娘详情失败")
  })
}

/** 解析资质证书图片 */
function getCertificationImages(certification) {
  if (!certification) return []

  // 如果是字符串，按逗号分割
  if (typeof certification === 'string') {
    return certification.split(',').filter(img => img.trim() !== '').map(img => {
      const trimmedImg = img.trim()
      // 如果是外部链接，直接返回
      if (isExternal(trimmedImg)) {
        return trimmedImg
      }
      // 如果是相对路径，添加基础API路径
      return import.meta.env.VITE_APP_BASE_API + trimmedImg
    })
  }

  // 如果是数组，直接处理
  if (Array.isArray(certification)) {
    return certification.filter(img => img && img.trim() !== '').map(img => {
      const trimmedImg = img.trim()
      if (isExternal(trimmedImg)) {
        return trimmedImg
      }
      return import.meta.env.VITE_APP_BASE_API + trimmedImg
    })
  }

  return []
}

/** 判断是否为外部链接 */
function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('request/request/export', {
    ...queryParams.value
  }, `request_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.certification-images {
  display: flex;
  flex-direction: column;
}

.certification-images .el-image {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.certification-images .el-image:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.certification-labels {
  margin-top: 5px;
}
</style>
